<template>
  <!-- 个人信息的详情 -->
  <div>
    <div class="userdata">
      <!-- <span>头像:<img src="../../../assets/pic.png" /></span> -->
      <span class="firstSpan"
        >头像:
        <img :src="'http://localhost:8081/' + userdataObj.user_pic" alt=""
      /></span>
      <span>用户名:{{ userdataObj.username }}</span>
      <span>昵称:{{ userdataObj.nickname }}</span>
      <span>ID:{{ userdataObj.id }}</span>
    </div>
    <!-- 注销和修改资料 -->
    <div class="buttonChange">
      <el-button @click="writeOff">注销</el-button>
      <el-button @click="changeInfo" type="primary">修改资料</el-button>
      <!-- token是
{{userdataObj}} -->
    </div>
    <!-- 显示修改资料的输入框 -->
    <el-form
      class="modifyForm"
      :label-position="labelPosition"
      label-width="120px"
      :model="formLabelAlign"
      v-if="seen"
    >
      <el-form-item label="修改昵称">
        <el-input v-model="formLabelAlign.newNickName"></el-input>
        <el-button @click="changeNickname">确定修改</el-button>
      </el-form-item>
      <!-- 修改头像 -->
      <el-form-item label="修改照片">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/my/updateAvatar"
          :headers="headers"
          name="avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button @click="changePic">确定修改</el-button>
      </el-form-item>
      <el-form-item label="修改密码">
        <el-input
          type="password"
          v-model="formLabelAlign.oldPassword"
          placeholder="请输入原密码"
          required
        ></el-input>
        <el-input
          type="password"
          v-model="formLabelAlign.newPassword1"
          placeholder="请输入新密码"
          required
        ></el-input>
        <el-input
          type="password"
          v-model="formLabelAlign.newPassword2"
          placeholder="请再次输入密码"
          required
        ></el-input>
        <el-button @click="changePassword">确定修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";

export default {
  name: "myInfo",
  data() {
    return {
      headers: {
        Authorization: this.$store.state.token,
      },
      userdataObj: {},
      picImg: "",
      tokenToInfo: "",
      labelPosition: "right",
      formLabelAlign: {
        newNickName: "",
        // 这是图片的名称
        newPic: "",
        oldPassword: "",
        newPassword1: "",
        newPassword2: "",
      },
      imageUrl: "",
      imageName: "",

      fileList: [],
      // 修改信息默认是false，不显示
      seen: false,
    };
  },
  props: ["userdataMyInfo"],
  // props: ['userdataMyInfo'],
  watch: {
    // 监听用户的信息
    userdataMyInfo: {
      handler(newscore, oldscore) {
        console.log(oldscore);
        this.userdataObj = newscore;
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.tokenToInfo = this.userdataMyInfo;
    this.picImg = this.userdataMyInfo.user_pic;
    var that = this;
    axios({
      method: "get",
      url: "http://localhost:8081/my/userinfo",
      async: false,
      headers: {
        Authorization: that.userdataMyInfo,
      },
    })
      .then((res) => {
        // 返回用户的信息
        that.userdataObj = res.data.data;
      })
      .catch((err) => {
        console.log("发生错误", err);
      });
  },
  methods: {
    // 注销
    // 它会根据token查询用户信息，当删除之后就会显示用户不存在，但是注销功能正常
    writeOff() {
      // console.log(this.userdataMyInfo)
      this.$confirm("此操作将在注销用户全部信息,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios({
            method: "post",
            url: "http://localhost:8081/my/deleteuser",
            async: false,
            // 身份认证的消息
            headers: {
              Authorization: this.userdataMyInfo,
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
            .then((res) => {
              console.log("删除的结果是", res);
            })
            .catch((err) => {
              console.log("发生错误", err);
            });

          this.$message({
            type: "success",
            message: "注销成功!",
          });
          this.$router.push({
            path: "/login",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    changeInfo() {
      console.log("修改资料");
      this.seen = !this.seen;
    },
    // 修改昵称
    changeNickname() {
      console.log("用户的id", this.userdataObj.id);
      let data = {
        id: this.userdataObj.id,
        nickname: this.formLabelAlign.newNickName,
      };
      axios({
        method: "post",
        url: "http://localhost:8081/my/userinfo",
        async: false,
        headers: {
          Authorization: this.userdataMyInfo,
          "Content-Type": "application/x-www-form-urlencoded",
        },
        data: qs.stringify({ ...data }),
      })
        .then((res) => {
          // this.$router.go(0);
          console.log("修改资料的", res);
          console.log("修改资料的", res.data.status);
          if (res.data.status == 0) {
            this.$router.go(0);
          } else {
            this.$message("昵称长度不能是空，且要在2到16位字符之间");
          }
        })
        .catch((err) => {
          console.log("发生错误", err);
        });
    },

    // 修改头像
    //上传图片的方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.imageName = file.name;

      this.$message({
        type: "success",
        message: "图片加载成功!",
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },

    async changePic() {
      if (this.imageName && this.imageUrl) {
        await axios({
          method: "post",
          url: "http://localhost:8081/my/updateAvatarUrl",
          headers: this.headers,
          data: {
            id: this.userdataObj.id,
            user_pic: this.imageName,
          },
        })
          .then(() => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          })
          .catch(() => {
            this.$message.error({
              message: "修改失败!",
            });
          });
      } else {
        this.$message.error({
          message: "请选择图片再上传!",
        });
      }
    },
    //changePassword,修改密码
    changePassword() {
      let data = {
        oldPwd: this.formLabelAlign.oldPassword,
        newPwd: this.formLabelAlign.newPassword1,
      };
      axios({
        method: "post",
        url: "http://localhost:8081/my/updatepwd",
        async: false,
        headers: {
          Authorization: this.userdataMyInfo,
          "Content-Type": "application/x-www-form-urlencoded",
        },
        data: qs.stringify({ ...data }),
      })
        .then((res) => {
          console.log("看下修改密码的情况", res);
          if (res.data.status == 0) {
            this.$message(res.data.message);
          } else {
            return;
          }
        })
        .catch((err) => {
          console.log("发生错误", err);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.userdata {
  display: flex;
  flex-direction: column;
  align-items: left;
  padding: 1.5rem 1rem;
  .firstSpan {
    // background-color: rgb(122, 72, 72);
    line-height: 30px;
  }
  span {
    margin-bottom: 1rem;

    img {
      width: 30px;
      height: 30px;
    }
  }
}
.buttonChange {
  margin-left: 3rem;
    // 使两个按钮同一行
  display: flex;
  .el-button {
    align-items: center;
    width: 10rem;
  }
}
.modifyForm {
  margin: 10px;
  .el-input {
    width: 80%;
  }
  .el-button {
    margin-top: 5px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
